package logger

import (
	"fmt"
	"io"
	"time"

	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gopkg.in/natefinch/lumberjack.v2"

	"path/filepath"
)

func InitLog() {
	// 设置logrus 的日志level
	switch viper.GetString("LogLevel") {
	case "PanicLevel":
		log.SetLevel(log.PanicLevel)
	case "FatalLevel":
		log.SetLevel(log.FatalLevel)
	case "ErrorLevel":
		log.SetLevel(log.ErrorLevel)
	case "WarnLevel":
		log.SetLevel(log.WarnLevel)
	case "InfoLevel":
		log.SetLevel(log.InfoLevel)
	case "DebugLevel":
		log.SetLevel(log.DebugLevel)
	case "TraceLevel":
		log.SetLevel(log.TraceLevel)
	default:
		log.SetLevel(log.InfoLevel)
	}

	fmt.Println("初始化日志")

	// Log as JSON instead of the default ASCII formatter.
	log.SetReportCaller(true)
	log.SetFormatter(&Formatter{})

	MaxAge := 28

	cvlslogger := lumberjack.Logger{
		Filename: viper.GetString("LogFile"),
		MaxSize:  1000,
		MaxAge:   MaxAge,
		Compress: true,
	}
	log.SetOutput(&cvlslogger)

	// Only log the warning severity or above.
	if gin.Mode() == gin.ReleaseMode {
		log.SetLevel(log.InfoLevel)
	}

	ginlogger := lumberjack.Logger{
		Filename: viper.GetString("GinLogFile"),
		MaxSize:  1000,
		MaxAge:   MaxAge,
		Compress: true,
	}
	gin.DefaultWriter = io.MultiWriter(&ginlogger)

	// 初始化appmonitor
	monlogger := lumberjack.Logger{
		Filename: viper.GetString("AppMonitorLogFile"),
		MaxSize:  1000,
		MaxAge:   MaxAge,
		Compress: true,
	}
	InitMonitor(&monlogger)

	logpath := filepath.Dir(viper.GetString("LogFile"))

	go func(cvlslogger *lumberjack.Logger, ginlogger *lumberjack.Logger, monlogger *lumberjack.Logger, logpath string) {
		for {
			// 定时备份、删除日志文件
			now := time.Now()
			next := now.Add(time.Hour * 24)
			next = time.Date(next.Year(), next.Month(), next.Day(), 0, 0, 0, 0, next.Location())
			t := time.NewTimer(next.Sub(now) - 1)
			// t := time.NewTimer(time.Second * 10)
			<-t.C
			cvlslogger.Rotate()
			ginlogger.Rotate()
			monlogger.Rotate()

			// 按规则重命名
			go func() {
				defer func() {
					if err := recover(); err != nil {
						log.Error("log recover")
					}
				}()
				time.Sleep(time.Minute * 10)
				RenameLog(logpath, 0, MaxAge)
			}()
		}
	}(&cvlslogger, &ginlogger, &monlogger, logpath)

	fmt.Println("初始化日志-完成")
}
